﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;

namespace NCRGEA.UserControls
{
    public partial class ucPayments_Add : UserControl
    {
        private int _MemberID;
        public int MemberID
        {
            get
            {
                return _MemberID;
            }
            set
            {
                _MemberID = value;
                RefreshData();
            }
        }

        public ucPayments_Add()
        {
            InitializeComponent();
            PopulateMenus();
        }

        private void PopulateMenus()
        {
            //Load payment methods
            DataTable tblPayMethods = AAL.DAL.ExecuteQuery("SELECT MethodID, Description FROM payMethods");
            if (tblPayMethods != null)
            {
                cmbMethods.DataSource = tblPayMethods;
                cmbMethods.DisplayMember = "Description";
                cmbMethods.SelectedIndex = 0;
            }

            //Load payment types
            DataTable tblPayTypes = AAL.DAL.ExecuteQuery("SELECT PayTypeID, Name FROM payTypes");
            if (tblPayTypes != null)
            {
                cmbPaymentType.DataSource = tblPayTypes;
                cmbPaymentType.DisplayMember = "Name";
                cmbPaymentType.SelectedIndex = 0;
            }
        }

        public void RefreshData()
        {

        }

        private void btnCancel_Click(object sender, EventArgs e)
        {
            this.Parent.Controls.Add(new ucPayments() { MemberID = _MemberID, Dock = DockStyle.Fill });
            this.Parent.Controls.Remove(this);
        }

        private void cmbMethods_Leave(object sender, EventArgs e)
        {
            //Force use to select a method
            if (cmbMethods.SelectedIndex == -1)
            {
                cmbMethods.SelectedIndex = 0;
                cmbMethods.Focus();
            }
        }

        private bool ValidateData()
        {
            double theDVal;
            if (!double.TryParse(txtAmount.Text, out theDVal))
            {
                MessageBox.Show("Invalid amount!");
                txtAmount.Focus();
                return false;
            }

            int theIVal;
            bool Parsed = false;
            Parsed = int.TryParse(txtReferenceNumber.Text, out theIVal);
            if (!Parsed && !string.IsNullOrWhiteSpace(txtReferenceNumber.Text))
            {
                MessageBox.Show("Invalid reference number!");
                txtReferenceNumber.Focus();
                return false;
            }
            return true;
        }

        private void btnSave_Click(object sender, EventArgs e)
        {
            if (!ValidateData())
                return;

            string memType = AAL.UAL.GetMemberStatus(_MemberID);
            if (memType == null)
                return;

            //If this member is a Lifetime member, they can't accept payments.
            if (memType == "Lifetime" || memType == "Remove" || memType == "Deceased" || memType == "Free")
            {
                MessageBox.Show(string.Format("This member is a {0} member and thus can not accept a payment!",memType));
                ShowPaymentsList();
                return;
            }

            double theDVal = double.Parse(txtAmount.Text);
            int? theIVal = null;
            int tmp;
            bool Parsed = int.TryParse(txtReferenceNumber.Text, out tmp);
            if (Parsed)
                theIVal = tmp;
            int MethodID = (int)((DataRowView)cmbMethods.SelectedValue)["MethodID"];
            int StaffID = ((frmMain)(this.ParentForm.MdiParent)).CurrentUser.StaffID;
            int PayTypeID = (int)((DataRowView)cmbPaymentType.SelectedValue)["PayTypeID"];
            string PayTypeName = ((DataRowView)cmbPaymentType.SelectedValue)["Name"].ToString();

            //Save the payment
            if (!AAL.UAL.SavePayment(_MemberID, MethodID, theIVal, theDVal, datePaymentDate.Value, StaffID, PayTypeID))
            {
                MessageBox.Show("An error occurred while adding the payment!");
                ShowPaymentsList();
                return;
            }

            //Only update the RenewalDate if this is a Dues payment.
            if (PayTypeName == "Dues")
            {
                DateTime? rDate = AAL.UAL.GetMemberRenewalDate(_MemberID);
                if (rDate == DateTime.MinValue)
                    rDate = null;
                DateTime renewalDate;
                if (rDate == null)
                {
                    renewalDate = datePaymentDate.Value.AddYears(1);
                }
                else
                {
                    switch (memType)
                    {
                        case "Active":
                        case "Overdue":
                            renewalDate = rDate.Value.AddYears(1);
                            break;
                        default:
                            renewalDate = datePaymentDate.Value.AddYears(1);
                            break;
                    }
                }

                if (!AAL.UAL.UpdateRenewalDate(_MemberID, renewalDate))
                    MessageBox.Show("An error occurred while updating the member's renewal date! You may have to manually update it!");
                else
                {
                    TriggerRenewalDateUpdate();
                    if (rDate == null)
                        AAL.UAL.CreateMemberLog(StaffID, _MemberID, "Updated RenewalDate to " + renewalDate.ToShortDateString() + ".");
                    else
                        AAL.UAL.CreateMemberLog(StaffID, _MemberID, "Updated RenewalDate from " + rDate.Value.ToShortDateString() + " to " + renewalDate.ToShortDateString() + ".");
                }
            }
            ShowPaymentsList();
        }

        private void TriggerRenewalDateUpdate()
        {
            if(this.ParentForm is Members.frmViewMember)
                ((Members.frmViewMember)this.ParentForm).ReloadMember();
        }

        private void ShowPaymentsList()
        {
            //Flip back to the list of payments
            this.Parent.Controls.Add(new ucPayments() { MemberID = _MemberID, Dock = DockStyle.Fill });
            this.Parent.Controls.Remove(this);
        }

        private void cmbPaymentType_Leave(object sender, EventArgs e)
        {
            if (cmbPaymentType.SelectedIndex == -1)
                cmbPaymentType.SelectedIndex = 0;
        }

    }
}
